package com.rollCall.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rollCall.entity.No;
import com.rollCall.mapper.NoMapper;
import com.rollCall.entity.result.Result;
import com.rollCall.service.StudentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 *  
 * @date 2025/2/5
 */
@RestController
@RequestMapping("/admin/roll-call")
@RequiredArgsConstructor
@Slf4j
@CrossOrigin
public class RollCallController {
    private final StudentService studentService;
    private final NoMapper noMapper;

    /**
     * 随机获取学生列表
     * @param no 班级编号
     * @param numberOfStudents 需要获取的学生数量
     * @param withReplacement 是否放回（0为不放回，1为放回）
     * @return 包含随机学生列表的结果对象
     */
    @GetMapping("/random-students")
    public Result<List<No>> getRandomStudents(
            @RequestParam int no,
            @RequestParam int numberOfStudents,
            @RequestParam int withReplacement // 是否放回
    ) {
        List<No> noList = noMapper.selectList(new QueryWrapper<No>().eq("no", no));
        if (noList.isEmpty()) {
            return Result.error("班级学生被抽光了呢!");
        }
        if (noList.size() < numberOfStudents) {
            return Result.error("挑选人数大于剩余人数!");
        }
        List<No> selectedStudents = new ArrayList<>();
        for (int i = 0; i < numberOfStudents; i++) {
            int index = RandomUtil.randomInt(0, noList.size());
            No no1 = noList.get(index);
            selectedStudents.add(no1);
            if (withReplacement == 0) {
                noList.remove(index);
                noMapper.deleteById(no1.getId());
            }
        }
        return Result.success(selectedStudents);
    }

    /**
     * 根据班级ID获取班级编号
     * @param classId 班级ID
     * @return 包含班级编号的结果对象
     */
    @GetMapping("/getNo/{classId}")
    public Result<Long> getNo(@PathVariable("classId") Long classId) {
        return Result.success(studentService.getNo(classId));
    }

}
